<?php
class dbConn {
    
    public $DB;
    public $sql;
    public $result;
    public $rows;
    public $_errInfo;
    public $DB_NAME;
    public $LAST_INSERT_ID;
    public $ROW_COUNT;
    public $limit_sql;
    public $limit;
    public $total;
    public $params;
	public $pagesize;
    
    // 构造函数
    public function  __construct() {
         $this->connection_db();
    }

    public function connection_db(){
         /* S DB sub */
        try{			
            $DSN = "mysql:host=".DBHOST.";port=".DBPORT.";dbname=".DBNAME;
            if(@$this->DB = new PDO($DSN, DBUSER, DBPWD, array(PDO::ATTR_PERSISTENT=>FALSE))){
            	$this->DB->query('SET NAMES UTF8');
                $this->DB->query("SET CHARACTER SET utf8");
                $this->DB->query("SET COLLATION_CONNECTION='utf8_general_ci'");
            }else{
                die("错误：<strong style=\"color:orange\">DB001</strong>");
            }
        }catch(Exception $e) {
            print "error002:".$e->getMessage();
            exit();
        }
    }
    
    // 析构函数
    public function  __destruct() {
        @$this->DB = null;
    }
    
    // 插入，记录LAST_INSERT_ID
    public function doInsert(){
    	$sth = $this->DB->prepare($this->sql);
        $sth->execute($this->params);
        if($sth->errorCode()!='00000'){
            print_r($sth->errorInfo());
            exit;
        }else{
            $resultId = $this->DB->lastInsertId();
            $this->LAST_INSERT_ID = $resultId;
            return $resultId;
        }
    }
	
    // 插入，更新，删除，不记录LAST_INSERT_ID
    public function doExecute($sql=''){
    	$sth = $this->DB->prepare($this->sql);
        $res = $sth->execute($this->params);
        if($sth->errorCode()!='00000'){
            print_r($sth->errorInfo());
            echo "<br />".$this->sql;
            exit;
        }
       
       	return $res;        
    }
    // 查询单条记录
    public function doResult($tag=''){
    	$this->result='';
    	$sth = $this->DB->prepare($this->sql);
        $rs = $sth->execute($this->params);
        try {
            $sth->setFetchMode(PDO::FETCH_ASSOC);
            $this->result = $sth->fetchAll();
       return      $this->result = $this->result?$this->result[0]:'';
			
        } catch (Exception $e) {
            echo "查询出错，错误信息如下：";
            echo $e->getMessage();
            exit;
        }
    }
	
// 查询单条记录new//2011/11/14 begin
    public function doResult2($tag=''){
    	$this->result='';
    	$sth = $this->DB->prepare($this->sql);
        $rs = $sth->execute($this->params);
        try {
            $sth->setFetchMode(PDO::FETCH_ASSOC);
            $this->result = $sth->fetchAll();
       		return $this->result = $this->result?$this->result[0]:'';
			
        } catch (Exception $e) {
            echo "查询出错，错误信息如下：";
            echo $e->getMessage();
            exit;
        }
    }
    //一个记录
    public function doResultOne(){
    	$this->doResult();
    	if ($this->result) {
        	foreach ($this->result as $item){
        		$r = $item;
        	}
    	}else{
    		$r='';
    	}
    	return $this->result=$r;
    }
//   new//2011/11/14 end 
// 查询集合 2011/11/15 begin
    public function doResultList2($tag=''){
    	$this->result='';
    	$sth = $this->DB->prepare($this->sql);
    	if($this->params){
            $rs = $sth->execute($this->params);
    	}else{
            $rs = $sth->execute();
    	}
		//$rs = $this->DB->query($this->sql);
        if($rs){
            try {
				return $this->result = $sth->fetchAll(PDO::FETCH_ASSOC);
            } catch (Exception $e) {
                echo "查询出错，错误信息如下：";
                echo $e->getMessage();
            	exit;
            }
        }
    }
    //2011/11/15 end
    // 查询集合
    public function doResultList($tag=''){
    	$this->result='';
    	$sth = $this->DB->prepare($this->sql);
    	if($this->params){
            $rs = $sth->execute($this->params);
    	}else{
            $rs = $sth->execute();
    	}
		//$rs = $this->DB->query($this->sql);
        if($rs){
            try {
                $this->result = $sth->fetchAll(PDO::FETCH_ASSOC);
            } catch (Exception $e) {
                echo "查询出错，错误信息如下：";
                echo $e->getMessage();
            	exit;
            }
        }
    }

    // 加载
    public function get($id,$key='id'){
    	$this->sql = "select * from ".$this->DB_NAME." where ".$key."=".$id;
    	$this->doResult();
    	return $this->result;
    }
    
    // 加载集合
    public function getAll($orderBy='id', $isAsc=false){
    	$this->sql = "select * from ".$this->DB_NAME." order by ".$orderBy." ".($isAsc ? "asc" : "desc");
    	$this->doResultList();
    	return $this->result;
    }
    
    // 加载集合
    public function getLimit($start=0, $end, $orderBy='id', $isAsc=false){
    	$this->sql = "select * from ".$this->DB_NAME." order by ".$orderBy." ".($isAsc ? "asc" : "desc")." limit ".$start.",".$end;
    	$this->doResultList();
    	return $this->result;
    }
    
    // 真删除
    public function realDelete($id , $key='id'){
    	$this->sql = "delete from ".$this->DB_NAME." where ".$key."=".$id;
    	$this->doExecute();
    }
    
    // 假删除
    public function fakeDelete($id){
    	$this->sql = "update ".$this->DB_NAME." set is_del=1 where id=".$id;
    	$this->doExecute();
    }
    
    // 获得表数目
    public function getCount($where='') {
    	$this->sql = "select count(*) as cou from ".$this->DB_NAME." ".$where;
    	$this->doResult();
    	return $this->result ? $this->result['cou'] : 0;
    }
    
    // 参数过滤
    public function clearParam($params = array()){
    	if($params){
            foreach ($params as $k=>$v){
                $tmpParams[$k] = $this->escape_string($v);
            }
            return $tmpParams;
    	}else{
            return array();
    	}
    }

    public function quoteValue($value){
        return $this->DB->quote($value);
    }
    
    // sql过滤
    public function escape_string($value, $like='') {
        if($value){
            // 去除斜杠
            if (get_magic_quotes_gpc()) {
                $value = stripslashes($value);
            }
            $value = $like ? $this->DB->quote("%".$value."%") : $this->DB->quote($value);
        }
        return $value;
    }

    // 深拷贝$this->result
    public function getListCopyFormResult(){
        $dstList = array();
        if (!is_array($this->result)) {
            return $dstList;
        }

        $srcList = $this->result;
        foreach ($srcList as $key => $val) {
            $dstList[$key] = $val;
        }
        return $dstList;
    }

    function _setLimit($PAGE, $page_size=PERPAGE){
        $sql = explode("from",$this->limit_sql);
        $sql = explode("order by",$sql[1]);

        $this->sql = "select count(*) as sum from ".$sql[0];
        $this->doResult();
        $this->total = $this->result && isset($this->result['sum']) ? $this->result['sum']: 0;
        $PAGE>(ceil($this->total/$page_size))?$PAGE=ceil($this->total/$page_size):$PAGE;
        $this->limit = ($PAGE-1 < 0 ? 0 : ($PAGE - 1))*$page_size;
    }
    
    public function reflash_data($id){
        //$mmc = memcache_init();
        //memcache_set($mmc, $id, $this->get($id));
    }
    
    public function sys_data_time(){
        $time = strtotime("now");
        $this->sql = "update sys set last_data_time='".$time."'";
        $this->doExecute();
        
        //$mmc = memcache_init();
        //memcache_set($mmc, "last_data_time", $time);
    }
}
?>